<template>
    <view class="layout">
        <!-- 导航栏 -->
        <view class="navbar">
            <view class="statusBar" :style="{height:getStatusBarHeight()+'px'}"></view>
            <view class="titleBar" :style="{height:getTitleBarHeight()+'px', marginLeft:getLeftIconLeft()+'px'}">
                <view class="nav-container">
                    <view class="left-icon">
                        <uni-icons type="left" size="30" @click="goBack"></uni-icons>
                    </view>
                    <view class="title">
                        <text>创作视频</text>
                    </view>
                    <view class="right-icon">
                        <uni-icons type="eye" size="30" @click="goHistory"></uni-icons>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 填充区域 -->
        <view class="fill" :style="{height:getNavBarHeight() +'px'}"></view>
        
        <!-- 主内容区 -->
        <view class="main-content">
            <!-- 导航选项卡 -->
            <view class="tab-nav">
                <view 
                  class="tab-item" 
                  :class="{active: activeTab === 'textToVideo'}"
                  @click="switchTab('textToVideo')"
                >
                    文生视频
                </view>
                <view 
                  class="tab-item" 
                  :class="{active: activeTab === 'imageToVideo'}"
                  @click="switchTab('imageToVideo')"
                >
                    图生视频
                </view>
            </view>
            
            <!-- 文生视频内容区 -->
            <view v-if="activeTab === 'textToVideo'" class="content-area">
                <!-- 创意描述部分 -->
                <view class="section">
                    <view class="section-title">创意描述</view>
                    <view class="input-container">
                        <textarea 
                          class="input-box" 
                          placeholder="请输入视频内容描述" 
                          maxlength="500"
                          v-model="videoQuery.prompt"
                        />
                        <view class="input-footer">
                            <view 
                              class="word-count-container"
                              @click="clearDescription"
                            >
                                <view class="ai-expansion" @click.stop="expandContent" v-if="videoQuery.prompt.trim() !== ''" :style="{'opacity': isExpanding ? '0.5' : '1', 'pointer-events': isExpanding ? 'none' : 'auto'}">
                                    <text class="ai-text">智能扩写</text>
                                </view>
                                <view class="t">
                                    <text>{{videoQuery.prompt.length}}/500</text>
                                    <uni-icons type="refresh" size="20"></uni-icons>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                
                <!-- 视频比例选择 -->
                <view class="section">
                    <view class="section-title">视频比例</view>
                    <view class="ratio-options">
                        <view 
                          class="ratio-item" 
                          v-for="(item, index) in ratioList" 
                          :key="index"
                          :class="{active: selectedRatio === item.value}"
                          @click="selectRatio(item.value)"
                        >
                            <view class="ratio-icon">{{item.value}}</view>
                            <text>{{item.label}}</text>
                        </view>
                    </view>
                </view>
                
                <!-- 灵感模式 -->
                <view class="section">
                    <view class="section-title">灵感模式</view>
                    <switch 
                      class="switch" 
                      :checked="isTextInspirationMode" 
                      @change="toggleTextInspirationMode"
                    />
                    <view class="description">
                        增加创意灵感，提升画面丰富度与表现力，可能会与输入提示词有差异。
                    </view>
                </view>
                
                <!-- 视频音效 -->
                <view class="section">
                    <view class="section-title">视频音效</view>
                    <switch 
                      class="switch" 
                      :checked="isTextSoundEffect" 
                      @change="toggleTextSoundEffect"
                    />
                    <view class="description">
                        为视频内容生成合适的音效，若无明确音效则生成背景音乐。
                    </view>
                </view>
            </view>
            
            <!-- 图生视频内容区 -->
            <view v-else class="content-area">
                <!-- 图片上传区域 -->
                <view class="section">
                    <view class="section-title">上传图片</view>
                    <view class="upload-container">
                        <!-- 上传框（未上传时显示） -->
                        <view v-if="!isImageUploaded" class="upload-box" @click="openImagePicker">
                            <view class="upload-icon">+</view>
                            <view class="upload-text">点击上传图片</view>
                            <view class="upload-tip">
                                您将上传照片用于AIGC服务，请确保您已获得权利人的同意，除本服务外，不得用于其他用途。
                            </view>
                        </view>

                        <!-- 已上传的图片（上传成功后显示） -->
                        <view v-else class="uploaded-image-container">
                            <image :src="uploadedImage" class="uploaded-image"></image>
                            <!-- 删除图标 -->
                            <view class="delete-icon" @click="deleteImage">
                                <uni-icons type="trash" size="24" color="#999"></uni-icons>
                            </view>
                        </view>
                    </view>
                </view>
                
                <!-- 创意描述 -->
                <view class="section">
                    <view class="section-title">创意描述(可选)</view>
                    <view class="input-container">
                        <textarea 
                          class="input-box" 
                          placeholder="请输入视频内容描述" 
                          maxlength="500"
                          v-model="videoQuery.prompt"
                        />
                        <view class="input-footer">
                            <view 
                              class="word-count-container"
                              @click="clearDescription"
                            >
                                <view class="ai-expansion" @click.stop="expandContent" v-if="videoQuery.prompt.trim() !== ''" :style="{'opacity': isExpanding ? '0.5' : '1', 'pointer-events': isExpanding ? 'none' : 'auto'}">
                                    <text class="ai-text">智能扩写</text>
                                </view>
                                <view class="t">
                                    <text>{{videoQuery.prompt.length}}/500</text>
                                    <uni-icons type="refresh" size="20"></uni-icons>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                
                <!-- 灵感模式 -->
                <view class="section">
                    <view class="section-title">灵感模式</view>
                    <switch 
                      class="switch" 
                      :checked="isImageInspirationMode" 
                      @change="toggleImageInspirationMode"
                    />
                    <view class="description">
                        增加创意灵感，提升画面丰富度与表现力，可能会与输入提示词有差异。
                    </view>
                </view>
                
                <!-- 视频音效 -->
                <view class="section">
                    <view class="section-title">视频音效</view>
                    <switch 
                      class="switch" 
                      :checked="isImageSoundEffect" 
                      @change="toggleImageSoundEffect"
                    />
                    <view class="description">
                        为视频内容生成合适的音效，若无明确音效则生成背景音乐。
                    </view>
                </view>
            </view>
        </view>
	
    <!-- 生成效果提示 -->
        <view class="creative-tips" v-if="isGenerating">
            <view class="animating-text">
                <span v-for="(char, index) in charList" :key="index" :style="{ 
                    color: currentIndex === index ? '#FFD700' : '#333', 
                    marginRight: '10rpx' 
                }">{{ char }}</span>
            </view>
        </view>
	
    <!-- 生成按钮 -->
    <view class="generate-btn-container">
        <button 
          class="generate-btn" 
          :disabled="isGenerateBtnDisabled"
          :style="generateBtnStyle"
          @click="generateVideo"
        >
          {{ remainingAttempts > 0 ? `立即生成 (${remainingAttempts}次机会)` : '机会已用完' }}
        </button>
    </view>
	
    </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIconLeft } from '@/utils/system.js';
import { ApigetVideoBypicture, ApigetVideoBytext, ApigetVideobyTime } from "/pages/api/video.js";
import { Apicustomer } from "/pages/api/common.js";
import { useInfoStore } from '/store/user.js';
import { useAuthStore } from '/store/token.js';

const u = useInfoStore();
// 导航选项卡状态
const activeTab = ref('textToVideo');
const remainingAttempts = ref(null); // 用户剩余生成次数
const user = ref(null);
const header = ref({});
// 生成视频的请求参数
const videoQuery = ref({
  userId: 0,
  width: 512,
  height: 512,
  addMusic: false,
  image: '',
  prompt: '',
  inspiration: false,
});

const switchTab = (tab) => {
  activeTab.value = tab;
  videoQuery.value.addMusic = false;
  videoQuery.value.inspiration = false;
  videoQuery.value.prompt = '';
};

// 获取生成的次数
const getCount = async () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const time = `${year}-${month}-${day}`;
  const res = await ApigetVideobyTime(time);
  remainingAttempts.value = 3 - res;
};

onMounted(async () => {
  user.value = u.userInfo
  videoQuery.value.userId = user.value.userId;
  getCount();
  // 获取 Pinia store
  const authStore = useAuthStore();
  // 初始化 header
  header.value["access-token"] = authStore.getToken;
});

onLoad((query)=>{
	if (query.data) {
	  const data = JSON.parse(decodeURIComponent(query.data));
	  if(data.image != null)
	  {
		  uploadedImage.value = data.image
		  isImageUploaded.value = true
		  activeTab.value = "imageToVideo"
	  }
	  videoQuery.value.prompt = data.description
	}
})


// 视频比例选择
const ratioList = ref([
  { value: '9:16', label: '竖屏' },
  { value: '3:4', label: '3:4' },
  { value: '1:1', label: '正方形' },
  { value: '4:3', label: '4:3' },
  { value: '16:9', label: '横屏' },
]);

const charList = ref(['视', '频', '正', '在', '生', '成', '中', '.', '.', '.']);
const currentIndex = ref(0);
const animationInterval = ref(null);

const startAnimation = () => {
  isGenerating.value = true;
  currentIndex.value = 0;
  if (animationInterval.value) {
    clearInterval(animationInterval.value);
  }
  animationInterval.value = setInterval(() => {
    currentIndex.value = (currentIndex.value + 1) % charList.value.length;
  }, 300);
};

// 文字生成视频
const getTextImage = async () => {
  try {
    const res = await ApigetVideoBytext(videoQuery.value);
    if (res) {
      uni.showToast({
        title: '视频生成成功请点击右上角查看',
        icon: 'none',
        duration: 5000,
      });
    } else {
      uni.showToast({
        title: '亲，我的能力有限，视频生成失败。',
        icon: 'none',
        duration: 2000,
      });
    }
  } catch (error) {
    console.error('生成视频失败:', error);
    uni.showToast({
      title: '亲，我的能力有限，视频生成失败。',
      icon: 'none',
      duration: 2000,
    });
  } finally {
    isGenerating.value = false;
    if (animationInterval.value) {
      clearInterval(animationInterval.value);
      animationInterval.value = null;
    }
  }
};

// 图片生成视频
const getImageVideo = async () => {
  try {
    const res = await ApigetVideoBypicture(videoQuery.value);
    if (res) {
      uni.showToast({
        title: '视频生成成功请点击右上角查看',
        icon: 'none',
        duration: 5000,
      });
    } else {
      uni.showToast({
        title: '亲，我的能力有限，视频生成失败。',
        icon: 'none',
        duration: 2000,
      });
    }
  } catch (error) {
    console.error('生成视频失败:', error);
    uni.showToast({
      title: '亲，我的能力有限，视频生成失败。',
      icon: 'none',
      duration: 2000,
    });
  } finally {
    isGenerating.value = false;
    if (animationInterval.value) {
      clearInterval(animationInterval.value);
      animationInterval.value = null;
    }
  }
};

const selectedRatio = ref('9:16');

const selectRatio = (ratio) => {
  selectedRatio.value = ratio;
  const ratios = {
    '9:16': { width: 512, height: 910 },
    '3:4': { width: 512, height: 682 },
    '1:1': { width: 512, height: 512 },
    '4:3': { width: 512, height: 384 },
    '16:9': { width: 512, height: 288 },
  };
  videoQuery.value.width = ratios[ratio].width;
  videoQuery.value.height = ratios[ratio].height;
};

// 文生视频灵感模式开关
const isTextInspirationMode = ref(false);

const toggleTextInspirationMode = (e) => {
  isTextInspirationMode.value = e.detail.value;
  videoQuery.value.inspiration = true;
};

// 文生视频视频音效开关
const isTextSoundEffect = ref(false);

const toggleTextSoundEffect = (e) => {
  isTextSoundEffect.value = e.detail.value;
  videoQuery.value.addMusic = e.detail.value;
};

// 图生视频灵感模式开关
const isImageInspirationMode = ref(false);

const toggleImageInspirationMode = (e) => {
  isImageInspirationMode.value = e.detail.value;
  videoQuery.value.inspiration = true;
};

// 图生视频视频音效开关
const isImageSoundEffect = ref(false);

const toggleImageSoundEffect = (e) => {
  isImageSoundEffect.value = e.detail.value;
  videoQuery.value.addMusic = e.detail.value;
};

// 清空描述
const clearDescription = () => {
  videoQuery.value.prompt = '';
};

// 图片上传相关
const uploadedImage = ref(null);
const isImageUploaded = ref(false);

// 打开图片选择器
const openImagePicker = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      uploadFile(tempFilePath);
    },
    fail: (err) => {
      console.error('选择图片失败:', err);
    },
  });
};

// 上传文件到服务器
const uploadFile = (filePath) => {
  uni.uploadFile({
    url: 'http://47.99.64.234:8000/app/file/upload',
    filePath: filePath,
    name: 'file',
    header: header.value,
    success: (res) => {
      const serverResponse = JSON.parse(res.data);
      if (serverResponse.code === 200) {
        uploadedImage.value = serverResponse.data;
        isImageUploaded.value = true;
        videoQuery.value.image = serverResponse.data;
      } else {
        uni.showToast({
          title: '上传失败',
          icon: 'none',
          duration: 2000,
        });
      }
    },
    fail: (err) => {
      console.error('上传失败:', err);
      uni.showToast({
        title: '上传失败',
        icon: 'none',
        duration: 2000,
      });
    },
  });
};

// 删除图片
const deleteImage = () => {
  uploadedImage.value = null;
  isImageUploaded.value = false;
  videoQuery.value.image = '';
};

// 生成按钮状态
const isGenerateBtnDisabled = computed(() => {
  if (isGenerating.value) {
    return true; // 如果正在生成视频，按钮禁用
  }

  if (activeTab.value === 'textToVideo') {
    return videoQuery.value.prompt.trim() === '';
  } else {
    return !isImageUploaded.value && videoQuery.value.prompt.trim() === '';
  }
});

// 生成中状态
const isGenerating = ref(false);

// 生成按钮样式
const generateBtnStyle = computed(() => {
  if (isGenerating.value || remainingAttempts.value <= 0) {
    return {
      backgroundColor: '#E1E7F6',
      color: '#7B61FF',
    };
  } else {
    return {
      backgroundColor: '#7B61FF',
      color: 'white',
    };
  }
});

// 生成视频
const generateVideo = () => {
  if (remainingAttempts.value <= 0) {
    uni.showToast({
      title: '您的生成次数已用完',
      icon: 'none',
      duration: 2000,
    });
    return;
  }

  isGenerating.value = true; // 设置生成中状态

  startAnimation();

  if (activeTab.value === 'textToVideo') {
    getTextImage();
  } else {
    getImageVideo();
  }
  remainingAttempts.value -= 1;
};

// 跳到视频生成的浏览历史
const goHistory = () => {
  uni.navigateTo({
    url: "/pages/tool/video/work",
  });
};

// 跳转回去
const goBack = () => {
  uni.navigateBack();
};

// 智能扩写功能
const expandContent = async() => {
    if (videoQuery.value.prompt.trim() !== '' && !isExpanding.value) {
		isExpanding.value = true; // 设置状态为正在扩写

		// 显示提示框
		uni.showToast({
		    title: "正在智能扩写...",
		    icon: "loading",
		    duration: 3000
		});
		
        // 构建提示词
        const content = "请根据我提供的提示词" + videoQuery.value.prompt.trim() + ",帮我对这个提示词进行优化.用中文你只要回复优化后的提示词就可以其他的不用回复"
        let res = await Apicustomer(content)
		
        // 扩写完成后恢复状态
        isExpanding.value = false;
		
        videoQuery.value.prompt = res;
    }
};

// 智能扩写状态
const isExpanding = ref(false);

onUnmounted(() => {
  if (animationInterval.value) {
    clearInterval(animationInterval.value);
  }
});
</script>

<style lang="scss" scoped>
.layout {
  .navbar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 10;
    background-color: #f5f7fa; /* 导航栏背景颜色 */
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    .titleBar {
      .nav-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 30rpx;
        height: 100%;
        .left-icon,
        .right-icon {
          display: flex;
          align-items: center;
        }
        .title {
          font-size: 36rpx;
          font-weight: bold;
          text-align: center;
          flex: 1;
          margin: 0 40rpx;
        }
      }
    }
  }

  .fill {
    width: 100%;
    background-color: #f8f8f8;
  }

  .main-content {
    margin-top: 20rpx;
    padding: 0 30rpx;

    .tab-nav {
      display: flex;
      align-items: center;
      margin-bottom: 40rpx;
      position: relative;
      .tab-item {
        padding: 10rpx 30rpx;
        border-radius: 50rpx;
        font-size: 30rpx;
        margin-right: 20rpx;
        position: relative;
        &.active {
          background-color: #7B61FF;
          color: white;
        }
      }
    }

    .content-area {
      .section {
        margin-bottom: 40rpx;
        .section-title {
          font-size: 32rpx;
          font-weight: bold;
          margin-bottom: 20rpx;
        }
        .upload-container {
          .upload-box {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 300rpx;
            background-color: #f5f7fa;
            border-radius: 10rpx;
            padding: 20rpx;
            .upload-icon {
              font-size: 60rpx;
              margin-bottom: 20rpx;
            }
            .upload-text {
              font-size: 28rpx;
              color: #666;
              margin-bottom: 20rpx;
            }
            .upload-tip {
              font-size: 24rpx;
              color: #999;
              text-align: center;
            }
          }
          .uploaded-image-container {
            position: relative;
            width: 200rpx;
            height: 200rpx;
            margin: 0 auto;
            .uploaded-image {
              width: 100%;
              height: 100%;
              border-radius: 10rpx;
            }
            .delete-icon {
              position: absolute;
              top: -24rpx;
              right: -24rpx;
              background-color: #fff;
              border-radius: 50%;
              width: 48rpx;
              height: 48rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
            }
          }
        }
        .input-container {
          background-color: #f5f7fa;
          border-radius: 10rpx;
          padding: 20rpx;
          margin-bottom: 20rpx;
          .input-box {
            width: 100%;
            height: 200rpx;
            font-size: 28rpx;
            color: #666;
          }
          .input-footer {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-top: 10rpx;
            .word-count-container {
              display: flex;
              justify-content: space-between;
              align-items: center;
              width: 100%;
              .ai-expansion {
                display: flex;
                align-items: center;
                cursor: pointer;
                background: linear-gradient(to right, #E6F7FF, #DEF2FF);
                border-radius: 40rpx;
                padding: 6rpx 15rpx;
                box-shadow: 0 2rpx 8rpx rgba(31, 155, 229, 0.2);
              }
              .t {
                display: flex;
                align-items: center;
				text{
					font-size: 15px;
					color: #808080;
				}
              }
              .ai-text {
                color: #1F9BE5;
                font-size: 24rpx;
                font-weight: 500;
              }
              .uni-icons {
                margin-left: 10rpx;
              }
            }
          }
        }
        .ratio-options {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          .ratio-item {
            width: 180rpx;
            background-color: #f5f7fa;
            border-radius: 10rpx;
            padding: 20rpx;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 20rpx;
            &.active {
              background-color: #e1e7f6;
              border: 2rpx solid #7B61FF;
            }
            .ratio-icon {
              width: 60rpx;
              height: 60rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-bottom: 10rpx;
            }
          }
        }
        .switch {
          float: right;
          transform: scale(0.8);
          margin-top: -60rpx;
        }
        .description {
          font-size: 24rpx;
          color: #999;
          margin-top: 10rpx;
          line-height: 1.6;
        }
      }
    }
  }

  .generate-btn-container {
    position: fixed;
    bottom: 30rpx;
    left: 0;
    right: 0;
    padding: 0 40rpx;
    z-index: 5;
    .generate-btn {
      border: none;
      border-radius: 50rpx;
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
      font-size: 36rpx;
      width: 100%;
      transition: all 0.3s;
      &[disabled] {
        background-color: #E1E7F6;
        color: #7B61FF;
      }
      &:not([disabled]) {
        background-color: #7B61FF;
        color: white;
      }
    }
  }

  .main-content {
    padding-bottom: 150rpx;
  }

  // AI生成中提示
  .creative-tips {
    width: 300px;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 100;
    .animating-text {
      font-size: 40rpx;
      font-weight: bold;
      text-align: center;
    }
  }
}
</style>